using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Diffluxum.CCScoring;
using System.Xml;
using System.Diagnostics;
using System.Configuration;

namespace CCScoringApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            _uxToDate.SelectionStart = DateTime.Today;
            _uxFromDate.SelectionStart = DateTime.Today.AddDays(-7);

            string buildPath = ConfigurationManager.AppSettings["BuildPath"];
            _pathTbx.Text = buildPath;
        }

        private void _generateBtn_Click(object sender, EventArgs e)
        {
            try
            {

                ProportionalGradingRule gradingRule = new ProportionalGradingRule(
                    1,
                    0,
                    1,
                    0,
                    0,
                    -6,
                    -6);
                CCScoringCoordinator scorer = new CCScoringCoordinator(
                    _pathTbx.Text,
                    new StandardTimeProvider(),
                    new UserScorerFactory(),
                    new BuildFileParser(),
                    gradingRule,
                    new BrokenBuildsSpanFactory());
                DateTime start = _uxFromDate.SelectionStart;
                DateTime stop = _uxToDate.SelectionStart.AddDays(1);


                List<IUserScorer> scores = new List<IUserScorer>(scorer.Score(start, stop));
                scores.Sort(new Comparison<IUserScorer>(Compare));

                CCScoringXmlFormatter formatter = new CCScoringXmlFormatter();
                StringBuilder builder = new StringBuilder();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = "   ";

                using (XmlWriter writer = XmlWriter.Create("CCScores.xml", settings))
                {
                    formatter.FormatXml(writer, scores);
                }

                Process p = new Process();
                p.StartInfo.FileName = "CCScores.xml";

                p.Start();

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings.Remove("BuildPath");
                config.AppSettings.Settings.Add("BuildPath", _pathTbx.Text);
                config.Save();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        int Compare(IUserScorer a, IUserScorer b)
        {
            return b.TotalPoints - a.TotalPoints;
        }


    }
}